package com.deer.wms.ware.task.web;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.base.system.model.SeedingCell;
import com.deer.wms.busine.tactic.model.PrintTempInfo;
import com.deer.wms.busine.tactic.service.PrintTempInfoService;
import com.deer.wms.busine.tactic.service.PrintTempUtils;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.StringUtil;
import com.deer.wms.project.root.util.StringUtils;
import com.deer.wms.ware.task.constant.WareTaskConstant;
import com.deer.wms.ware.task.model.SO.*;
import com.deer.wms.ware.task.model.out.OutDetail;
import com.deer.wms.ware.task.model.out.OutInfoVO;
import com.deer.wms.ware.task.model.out.OutMaster;
import com.deer.wms.ware.task.model.out.OutMasterDto;
import com.deer.wms.ware.task.model.pickTask.PickTask;
import com.deer.wms.ware.task.service.OutDetailService;
import com.deer.wms.ware.task.service.OutMasterService;
import com.deer.wms.ware.task.service.PickTaskService;
import com.deer.wms.ware.task.service.SoMasterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.rmi.ServerError;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 发运单master 前端控制器
 * </p>
 *
 * @author luowei
 * @since 2022-04-18 17:42:23
 */
@RestController
@RequestMapping("/out/master")
@Transactional
public class OutMasterController {
    @Autowired
    private OutMasterService outMasterService;
    @Autowired
    private OutDetailService outDetailService;

    /**
     * list查询
     * @param criteria 查询条件
     * @return Result
     */
    @GetMapping("/list")
    public Result list(SoMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<OutMasterDto> list = outMasterService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/sign/detail")
    public Result signDetail(String billNo) {
        OutMaster outMaster = outMasterService.getOneByField("bill_no", billNo);
        OutInfoVO outInfoVO = new OutInfoVO();
        outInfoVO.setOutBillCode(outMaster.getBillNo());
        outInfoVO.setSendPerson(outMaster.getCreateUserName());
        outInfoVO.setSendDate(LocalDateTimeUtil.format(outMaster.getOutTime(), "yyyy-MM-dd HH:mm:ss"));
        List<OutDetail> outDetails = outDetailService.getListByField("bill_no", billNo);
        outInfoVO.setDetails(outDetails);
        return ResultGenerator.genSuccessResult(outInfoVO);
    }

    @PostMapping("/sign/confirm")
    public Result signConfirm(MultipartFile file, String outBillCode) throws IOException {
        try {
            outMasterService.signConfirm(file, outBillCode);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return  ResultGenerator.genSuccessResult();
    }

    @GetMapping("/list2")
    public Result list2(SoMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<OutMasterDto> list = outMasterService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/detail/list")
    public Result detailList(String billNo) {
//        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<OutDetail> outDetails = outDetailService.getListByField("bill_no", billNo);
        PageInfo pageInfo = new PageInfo(outDetails);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation(value = "查询汇总好的出库单明细")
    @GetMapping("/detail/groupList")
    public Result detailGroupList(String billNo) {
        List<OutDetail> outDetails = outDetailService.detailGroupList(billNo);
        PageInfo pageInfo = new PageInfo(outDetails);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @PostMapping("/sendOut")
    public Result sendOut(@RequestBody Merge merge, @ApiIgnore @User CurrentUser currentUser) {
        List<OutMaster> outMasters = outMasterService.list(new QueryWrapper<OutMaster>().in("bill_no", merge.getBillNos()));
        for (OutMaster outMaster : outMasters) {
            if (ObjectUtil.equal(outMaster.getState(), WareTaskConstant.OUT_STATE_INIT)) {
                outMasterService.confirmOutBill(outMaster, currentUser);
            }
        }
        return ResultGenerator.genSuccessResult();
    }

    @Autowired
    private PrintTempInfoService printTempInfoService;

    @GetMapping("/print")
    @Transactional
    public Result print(String billNo) {
        //获取出库单信息
        if (StringUtils.isEmpty(billNo)) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "单号异常");
        }
        OutMaster outMaster = outMasterService.getOneByField("bill_no", billNo);
        if (ObjectUtil.isNull(outMaster)) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "未找到相应订单！");
        }
        List<OutDetail> list = outDetailService.getListByField("bill_no", billNo);
        //获取电子面单模板
        PrintTempInfo printTempInfo = printTempInfoService.getById(60);
        if (printTempInfo == null) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "未找到匹配的发运单模板");
        }
        String html = printTempInfo.getTempHtml();
        Document doc = Jsoup.parse(html);
        //删除不显示的
        doc.select(".dis-none").remove();
        //直线中间蓝点的问题
        doc.select(".line-handle").remove();

        PrintTempUtils.setTempData("SHIP_BILL_NO_BAR_CODE", outMaster.getBillNo(), doc, "barCode");
//        PrintTempUtils.setTempData("SHIP_BILL_NO_QR_CODE", "billNo="+outMaster.getBillNo(), doc, "qrCode");
        PrintTempUtils.setTempData("SHIP_BILL_NO_QR_CODE", "http://172.20.10.4:9011/signAccept/index.html?billNo="+outMaster.getBillNo(), doc,
                "qrCode");
        PrintTempUtils.setTempData("SHIP_BILL_NO", outMaster.getBillNo(), doc, "text");
//        PrintTempUtils.setTempData("TRADE_NO", , doc, "text");
//        PrintTempUtils.setTempData("SHOP_NAME", outMaster.getShop(), doc, "text");
//        PrintTempUtils.setTempData("SENDER_NAME", outMaster.getShipLinkMan(), doc, "text");
//        PrintTempUtils.setTempData("SENDER_ADDRESS", outMaster.getShipDetailAddress(), doc, "text");
//        PrintTempUtils.setTempData("SENDER_PROVINCE", outMaster.getShipProvince(), doc, "text");
//        PrintTempUtils.setTempData("SENDER_CITY", outMaster.getShipCity(), doc, "text");
//        PrintTempUtils.setTempData("SENDER_AREA", outMaster.getShipArea(), doc, "text");
//        PrintTempUtils.setTempData("SENDER_MOBILE", outMaster.getShipLinkPhone(), doc, "text");
//        PrintTempUtils.setTempData("SENDER_COUNTRY", outMaster.getShipCountry(), doc, "text");

//        PrintTempUtils.setTempData("RECEIVER_NAME", outMaster.getLinkMan(), doc, "text");
//        PrintTempUtils.setTempData("RECEIVER_ADDRESS", outMaster.getDetailAddress(), doc, "text");
//        PrintTempUtils.setTempData("RECEIVER_PROVINCE", outMaster.getProvince(), doc, "text");
//        PrintTempUtils.setTempData("RECEIVER_CITY", outMaster.getCity(), doc, "text");
//        PrintTempUtils.setTempData("RECEIVER_AREA", outMaster.getArea(), doc, "text");
//        PrintTempUtils.setTempData("RECEIVER_MOBILE", outMaster.getLinkPhone(), doc, "text");
//        PrintTempUtils.setTempData("RECEIVER_COUNTRY", outMaster.getCountry(), doc, "text");
//
//        PrintTempUtils.setTempData("ORDER_TOTAL_PRICE", outMaster.getTotalPrice(), doc, "text");


//        PrintTempUtils.setTempData("LMSC", outMaster.getLastMileSortingCode(), doc, "text");
//        PrintTempUtils.setTempData("LMD", outMaster.getLastMileDestination(), doc, "text");
//        PrintTempUtils.setTempData("LMLC", outMaster.getLastMileLineCode(), doc, "text");
//        PrintTempUtils.setTempData("EXT1", outMaster.getSoUdfHs1(), doc, "text");
//        PrintTempUtils.setTempData("EXT2", outMaster.getSoUdfHs2(), doc, "text");
//        PrintTempUtils.setTempData("EXT3", outMaster.getSoUdfHs3(), doc, "text");

//        if (doc.getElementById("FULL_ITEMS_DETAIL_STR") != null) {
//            Element parent = doc.getElementById("FULL_ITEMS_DETAIL_STR2");
//
//            Element newEle = parent.getElementById("FULL_ITEMS_DETAIL_STR");
//            doc.select("#FULL_ITEMS_DETAIL_STR").remove();
//            for (SoDetail soDetail : list) {
//                Element newEle2 = newEle.clone();
//                PrintTempUtils.setTempData("FULL_ITEMS_DETAIL_STR", soDetail.getItemCode() + "" + soDetail.getItemName() + " * " + soDetail.getOrderQuantity(), newEle2, "text");
//                newEle2.appendTo(parent);
//            }
//        }
//
//        StringBuilder stringBuilder = new StringBuilder();
//        for (SoDetail soDetail : list) {
//            stringBuilder = stringBuilder.append(soDetail.getItemCode()).append("  ").append(soDetail.getItemName()).append(" X ")
//                    .append(soDetail.getOrderQuantity().intValue()).append("; ");
//        }
//        PrintTempUtils.setTempData("FULL_SKU_STR", stringBuilder.toString(), doc, "text");

        if (doc.getElementById("ITEM_LIST_DETAIL") != null) {
            Element FULL_ITEMS_DETAIL_TABLE = doc.getElementById("FULL_ITEMS_DETAIL_TABLE");
            Element tbody = FULL_ITEMS_DETAIL_TABLE.getElementsByTag("tBody").get(0);
            Element ITEM_LIST_DETAIL = tbody.getElementById("ITEM_LIST_DETAIL");
            Integer colspan = 0;
            for (OutDetail outDetail : list) {
                Element newEle = ITEM_LIST_DETAIL.clone();
                colspan += PrintTempUtils.setTempData("ITEM_LIST_DETAIL_SKU", outDetail.getItemCode(), newEle, "text");
                colspan += PrintTempUtils.setTempData("ITEM_LIST_DETAIL_NAME_CN", outDetail.getItemName(), newEle, "text");
                colspan += PrintTempUtils.setTempData("ITEM_LIST_DETAIL_QUANTITY", outDetail.getDeliveryQuantity(), newEle, "text");

                newEle.appendTo(tbody);
            }
            ITEM_LIST_DETAIL.remove();
        }


        //doc在创建时里面包含了html head body等节点  不需要
        Element labelContent = doc.getElementsByAttributeValue("class", "label-content").get(0);
        String tempHtml = labelContent.toString();
        return ResultGenerator.genSuccessResult(tempHtml);
    }
}

